package com.guochenglang.www.web.filter;

import com.guochenglang.www.util.jwts.JwtUtils;
import com.guochenglang.www.util.connect.Config;
import io.jsonwebtoken.Claims;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Properties;

/**
 * 登录过滤器，防止未登录访问业务
 *
 * @author GuoChenglang
 */
@WebFilter("/*")
public class LogInFilter implements Filter {
    /**
     * 非过滤文件
     */
    private static ArrayList<String> notFilter = new ArrayList<>();


    /**
     * 获取登录组件，防止过滤登录功能
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        //读取properties文件
        Properties prop = new Properties();
        InputStream inputStream = Config.class.getClassLoader().getResourceAsStream("LogInFilter.properties");
        try {
            prop.load(inputStream);
            String[] arrayElements = prop.getProperty("arrayElements").split(",");
            //将白名单加入到集合中
            Collections.addAll(notFilter, arrayElements);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //获得url地址
        String url = request.getRequestURI();
        //放行非过滤文件
        for (String s : notFilter) {
            if (url.contains(s)) {
                filterChain.doFilter(request, response);
                return;
            }
        }
        HttpSession session = request.getSession();
        if (session != null) {
            //获得存储的jwt令牌
            Object jwt = session.getAttribute("user");
            //没有令牌，则返回登录页面
            if (jwt == null) {
                response.sendRedirect(request.getContextPath() + "/LogIn.html");
                return;
            }
            //判断令牌是否已经过期
            try {
                Claims claims = JwtUtils.parseJwt(jwt.toString());
                filterChain.doFilter(request, response);
            } catch (Exception e) {
                response.sendRedirect(request.getContextPath() + "/LogIn.html");
            }

        }
    }

    @Override
    public void destroy() {

    }
}
